package com.xudu.service.impl;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xudu.entity.User;
import com.xudu.mapper.UserMapper;
import com.xudu.service.IFileService;
import com.xudu.utils.AESUtil;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

/**
 * ClassName: FileServiceImpl
 * Description:
 *
 * @Author xudu
 * @Create 2024/4/21
 */
@Service
@Component
public class FileServiceImpl extends ServiceImpl<UserMapper, User> implements IFileService {

    @Autowired
    private UserMapper userMapper;

    @Value("${import.imgPath}")
    private String imgPath;
    @SneakyThrows
    @Override
    public boolean uploadPhoto(User user, MultipartFile photo) {

        String KEY = "1234567812345678";
        String encrypt = AESUtil.encrypt(user.getPassword(),KEY);
        user.setPassword(encrypt);
        // 设置文件存储路径
        //String FILE_DIRECTORY = "E:/upload/";
        String FILE_DIRECTORY = imgPath;

        //File.separator相当于“\”
        //获得文件存储路径
        String filePath = FILE_DIRECTORY + photo.getOriginalFilename();

        // 保存文件在指定路径
        photo.transferTo(new File(filePath));

        //为图片存储路径赋值
        user.setAvatarpath(filePath);
        int i = userMapper.insert(user);
        if (i>0){
            return true;
        }else {
            return false;
        }

    }

    @SneakyThrows
    @Override
    public void downloadPhoto(User user, HttpServletResponse response) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getUsername,user.getUsername());
        User dbuser = userMapper.selectOne(queryWrapper);

        File photoFile = new File(dbuser.getAvatarpath());
        byte[] bytes = FileUtil.readBytes(photoFile); //FileUtil是hutool工具封装的工具类
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();

    }


}
